<?php
namespace app\api\controller;

use Gregwar\Image\Image;
use think\Controller;
use think\Request;
use think\Session;
use OSS\OssClient;
use OSS\Core\OssException;

/**
 * 通用上传接口
 * Class Upload
 * @package app\api\controller
 */
class Fileuploadlayui extends Controller
{
    protected function _initialize()
    {

        parent::_initialize();
        if (!Session::has('admin_id')) {
            $result = [
                'code' => 1,
                'message' => '未登录'
            ];

            return json($result);
        }
    }

    /**
     * 实例化阿里云oos
     * @return object 实例化得到的对象
     */
    function new_oss()
    {
        vendor('Alioss.autoload');
        $config = config("ALIOSS_CONFIG");
        $oss    = new OssClient($config['KEY_ID'], $config['KEY_SECRET'], $config['END_POINT']);
        return $oss;
    }

    /**
     * 上传文件到oss并删除本地文件
     * @param  string $path 文件路径
     * @return bollear      是否上传
     */
    function oss_upload($path)
    {
        // 获取配置项
        $bucket = config('ALIOSS_CONFIG.BUCKET');
        // 先统一去除左侧的.或者/ 再添加./
        $oss_path = ltrim($path, './');
        $path     = $oss_path;

        if (file_exists($path)) {
            // 实例化oss类
            $oss = $this->new_oss();
            // 上传到oss
            $oss1 = $oss->uploadFile($bucket, $oss_path, $path);
            // 如需上传到oss后 自动删除本地的文件 则删除下面的注释
            return $oss1;
        }
        return false;
    }


    /**
     * 通用上传接口
     * @return \think\response\Json
     */
    public function upload(Request $request)
    {

        $switch_shuiying = $request->param('shuiying');
        //上传需要水印

        foreach ($_FILES as $key => $value) {
            $file_key = $key;
        }

        $config = [
            'size' => 42949672960,
            'ext' => 'jpg,jpeg,gif,png,bmp,mp3,wav,wma,mp4,avi,wmv,rm,rmvb,mpg,mpeg,3gp,mov,flv,mkv,caf'
        ];

        $res_rules = $request->file($file_key)->check($config);

        if (empty($res_rules)) {
            $result = [
                'code' => 1,
                'message' => '文件验证不通过'
            ];
            return json($result);
        }
        $object_name  = $request->file($file_key)->getInfo('name');//拿到文件名
        $explod_obect = pathinfo($object_name);//拆分
        $ali_new_name = md5($explod_obect['filename']) . '.' . $explod_obect['extension'];//加密
        $date         = date('Y-m-d-H-i', time());//时间
        if ($switch_shuiying == 'on') {

            //先上传到本地进行水印处理
            $info = $request->file($file_key)->move(ROOT_PATH . 'public' . DS . 'uploads');
            if ($info) {
                $upload_file_path = ROOT_PATH . 'public' . DS . 'uploads/' . $info->getSaveName();


                /*打开图片*/ //1、配置图片路径
                $src = $upload_file_path;
                //2、获取图片信息
                $info = getimagesize($src);
                //3、获取图片类型
                $type = image_type_to_extension($info[2], false);
                //4、在内存中创建图像
                $createImageFunc = "imagecreatefrom{$type}";
                //5、把图片复制内存中
                $image = $createImageFunc($src);
                /*操作图片*/
                //1、设置水印图片路径
                $imageMark = ROOT_PATH . '/public/alpha_test_4.png';
                //2、获取水印图片基本信息
                $markInfo = getimagesize($imageMark);

                //获取主图信息
                $dst_info          = getimagesize($src);
                $water_need_width  = ceil($dst_info[0] / 6);
                $water_need_height = ceil(($water_need_width * $markInfo[1]) / $markInfo[0]);

                $water_need_path = ROOT_PATH . '/public/water_need/alpha_test_4.png';
                $res_cut = Image::open($imageMark)->zoomCrop($water_need_width, $water_need_height)->save($water_need_path);
                usleep(500000);
                if ($res_cut) {
                    $water_need_info = getimagesize($water_need_path);
                }

                //3、获取水印图片类型
                $markType = image_type_to_extension($markInfo[2], false);
                //4、在内存创建图像
                $markCreateImageFunc = "imagecreatefrom{$markType}";
                //5、把水印图片复制到内存中
                $water = $markCreateImageFunc($water_need_path);
                //特别处理，设置透明

                imagecopy($image, $water, $dst_info[0] - $water_need_info[0] - 25,
                    $dst_info[1] - $water_need_info[1] - 25, 0, 0, $water_need_info[0],
                    $water_need_info[1]);

                //7、销毁水印图片
                imagedestroy($water);
                /* 输出图片 */
                //1、浏览器输出

                $outputfunc = "image{$type}";
                //2、保存图片
                $outputfunc($image, $upload_file_path);
                /* 销毁图片 */
                imagedestroy($image);

                try {
                    // 获取配置项
                    $bucket = config('ALIOSS_CONFIG.BUCKET');
                    // 实例化oss类
                    $oss = $this->new_oss();
                    // 上传到oss
                    $oss1 = $oss->uploadFile($bucket, 'uploads/' . $date . '/' . $file_key . '/' . $ali_new_name,
                        $upload_file_path);
                    if ($oss1) {
                        $url_return = $oss1['info']['url'];
                        $url_return = str_replace('http://', 'https://', $url_return);
                        $result = [
                            'code' => 0,
                            'msg' => "success",
                            'data' => [
                                "src" => $url_return,
                                "title" => ''
                            ]
                        ];

                    } else {
                        $result = [
                            'code' => 1,
                            'msg' => $request->file($file_key)->getError(),
                            'data' => [
                                "src" => '',
                                "title" => ''
                            ]
                        ];
                    }
                    unlink($src);//删除本地文件
                    return json($result);
                } catch (OssException $e) {

                    $result = [
                        'code' => 1,
                        'msg' => $e->getMessage(),
                        'data' => [
                            "src" => '',
                            "title" => ''
                        ]
                    ];
                    return json($result);
                }


            } else {
                $result = [
                    'code' => 1,
                    'msg' => $request->file($file_key)->getError(),
                    'data' => [
                        "src" => '',
                        "title" => ''
                    ]
                ];
                return json($result);
            }
        } else {//直传
            try {
                // 获取配置项
                $bucket = config('ALIOSS_CONFIG.BUCKET');
                // 实例化oss类
                $oss  = $this->new_oss();
                $path = $request->file($file_key)->getRealPath();
                // 上传到oss
                $oss1 = $oss->uploadFile($bucket, 'uploads/' . $date . '/' . $file_key . '/' . $ali_new_name, $path);
                if ($oss1) {
                    $url_return = $oss1['info']['url'];
                    $url_return = str_replace('http://', 'https://', $url_return);
                    $result = [
                        'code' => 0,
                        'msg' => "success",
                        'data' => [
                            "src" => $url_return,
                            "title" => ''
                        ]
                    ];

                } else {
                    $result = [
                        'code' => 1,
                        'msg' => "error",
                        'data' => [
                            "src" => '',
                            "title" => ''
                        ]
                    ];
                }
                return json($result);
            } catch (OssException $e) {
                $result = [
                    'code' => 1,
                    'msg' => $e->getMessage(),
                    'data' => [
                        "src" => '',
                        "title" => ''
                    ]
                ];
                return json($result);
            }
        }



    }


    private function check_dir($dirname = '')
    {
        if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
            return ['code' => 'ERROR', 'info' => '文件创建失败'];
        } else {
            if (!is_writeable($dirname)) {
                return ['code' => 'ERROR', 'info' => '文件不可写'];
            } else {
                return ['code' => 'SUCCESS', 'info' => 'SUCCESS_DIR'];
            }
        }
    }

    /**
     * 删除oss上指定文件
     * @param  string $object 文件路径 例如删除 /Public/README.md文件  传Public/README.md 即可
     */
    function oss_delet_object($object)
    {
        // 实例化oss类
        $oss = $this->new_oss();
        // 获取bucket名称
        $bucket = config('ALIOSS_CONFIG.BUCKET');
        $test   = $oss->deleteObject($bucket, $object);
    }
}